package com.linhai.scm.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.linhai.scm.entity.base.User;
import com.linhai.scm.service.IUserService;

@WebServlet("/User.h")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private IUserService service;
    
    public UserServlet() {
        super();
    }
    
    public void init(ServletConfig config) throws ServletException {
        super.init(config);/*
        service=(IUserService)WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServletContext()).getBean(
                        "userService");
        */
        System.out.println("UserServlet初始化");
        
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		java.io.PrintWriter out=response.getWriter();
		String msg="";
		String strJson="";
		if(null==service){
			msg="失败，系统初始化错误！";
			strJson="{\"ok\":false,\"msg\":\"" + msg + "\"}";
			out.write(strJson);
			return;
		}
		String _id=request.getParameter("id");
		long id=null==_id?0L:Long.parseLong(_id);
		String uName=request.getParameter("uName");
		String uPwd=request.getParameter("uPwd");
		User entity=service.get(id);
		if(null==entity){
			System.out.println("u==null");
			if(0<id){
				System.out.println("无法找到记录");
				msg="无法找到该记录，请确认该记录是否存在！";
				strJson="{\"ok\":false,\"msg\":\"" + msg + "\"}";
				out.write(strJson);
				return;
			}else{
				System.out.println("新建User");
				//out.write("新建User");
				entity=new User();
			}
		}
		entity.setUserName(uName.trim());
		entity.setUserPwd(uPwd.trim());
		if(0==id){
			long newID=(Long)service.insert(entity);
			System.out.println("添加User完成！");
			//out.write("添加User完成");
			msg="添加User完成,新生成的ID为：" + newID;
			strJson="{\"ok\":true,\"msg\":\"" + msg + "\"}";
		}else{
			service.update(entity);
			System.out.println("更新User完成！");
			//out.write("更新User完成");
			msg="更新User完成";
			strJson="{\"ok\":true,\"msg\":\"" + msg + "\\r\\n" + entity.getUserName() + "\"}";
		}
		out.write(strJson);
	}

}
